package top.yokey.shopai.store.activity;

import android.content.Intent;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.Objects;

import top.yokey.shopai.R;
import top.yokey.shopai.store.adapter.StoreListAdapter;
import top.yokey.shopai.store.viewmodel.StoreListVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.arouter.ARoutePath;
import top.yokey.shopai.zcom.base.BaseActivity;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.recycler.LineDecoration;
import top.yokey.shopai.zcom.util.ConvertUtil;
import top.yokey.shopai.zcom.util.VerifyUtil;
import top.yokey.shopai.zcom.view.PullRefreshView;
import top.yokey.shopai.zcom.voice.XFVoiceDialog;
import top.yokey.shopai.zsdk.bean.StoreListBean;
import top.yokey.shopai.zsdk.data.GoodsData;
import top.yokey.shopai.zsdk.data.ShopSearchData;

@Route(path = ARoutePath.STORE_LIST)
public class StoreListActivity extends BaseActivity {

    private final ShopSearchData data = new ShopSearchData();
    private final ArrayList<StoreListBean> arrayList = new ArrayList<>();
    private final StoreListAdapter adapter = new StoreListAdapter(arrayList);
    private Toolbar mainToolbar = null;
    private AppCompatEditText toolbarEditText = null;
    private AppCompatImageView toolbarImageView = null;
    private AppCompatImageView voiceImageView = null;
    private FloatingActionButton areaButton = null;
    private PullRefreshView mainPullRefreshView = null;
    private StoreListVM vm = null;

    @Override
    public void initView() {

        setContentView(R.layout.activity_store_list);
        mainToolbar = findViewById(R.id.mainToolbar);
        toolbarEditText = findViewById(R.id.toolbarEditText);
        toolbarImageView = findViewById(R.id.toolbarImageView);
        voiceImageView = findViewById(R.id.voiceImageView);
        areaButton = findViewById(R.id.areaButton);
        mainPullRefreshView = findViewById(R.id.mainPullRefreshView);

    }

    @Override
    public void initData() {

        setToolbar(mainToolbar);
        observeKeyborad(R.id.mainRelativeLayout);
        toolbarEditText.setText(data.getKeyword());
        toolbarEditText.setSelection(VerifyUtil.isEmail(data.getKeyword()) ? 0 : data.getKeyword().length());
        toolbarEditText.setHint(R.string.pleaseInputKeyword);
        toolbarImageView.setImageResource(R.drawable.ic_action_menu);
        mainPullRefreshView.setAdapter(adapter);
        mainPullRefreshView.setItemDecoration(new LineDecoration(App.get().dp2Px(16), true));
        vm = getVM(StoreListVM.class);
        data.setPage("1");
        getData();

    }

    @Override
    public void initEvent() {

        toolbarEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                data.setKeyword(Objects.requireNonNull(toolbarEditText.getText()).toString());
                data.setPage("1");
                hideKeyboard();
                getData();
            }
            return false;
        });

        voiceImageView.setOnClickListener(view -> XFVoiceDialog.get().show(get(), result -> {
            toolbarEditText.setText(result);
            toolbarEditText.setSelection(result.length());
            data.setKeyword(result);
            data.setPage("1");
            getData();
        }));

        toolbarImageView.setOnClickListener(view -> App.get().start(get(), ARoutePath.STORE_CLASS, Constant.CODE_CATE));

        areaButton.setOnClickListener(view -> App.get().start(get(), ARoutePath.MAIN_AREA, Constant.CODE_AREA));

        mainPullRefreshView.setOnClickListener(view -> {
            if (mainPullRefreshView.isError() || arrayList.size() == 0) {
                data.setPage("1");
                getData();
            }
        });

        mainPullRefreshView.setOnRefreshListener(new PullRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                data.setPage("1");
                getData();
            }

            @Override
            public void onLoadMore() {
                getData();
            }
        });

        adapter.setOnItemClickListener(new StoreListAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, StoreListBean bean) {
                App.get().startStore(bean.getStoreId());
            }

            @Override
            public void onClickGoods(int position, int itemPosition, StoreListBean.SearchListGoodsBean bean) {
                App.get().startGoods(new GoodsData(bean.getGoodsId()));
            }
        });

    }

    @Override
    public void initObserve() {

        vm.getStoreLiveData().observe(this, list -> {
            if (data.getPage().equals("1")) arrayList.clear();
            data.setPage((ConvertUtil.string2Int(data.getPage()) + 1) + "");
            arrayList.addAll(list);
            mainPullRefreshView.setComplete();
        });

        vm.getHasMoreLiveData().observe(this, bool -> mainPullRefreshView.setCanLoadMore(bool));

        vm.getErrorLiveData().observe(this, bean -> {
            if (bean.getCode() == 1) {
                if (arrayList.size() == 0) {
                    mainPullRefreshView.setError(bean.getReason());
                } else {
                    ToastHelp.get().show(bean.getReason());
                }
            }
        });

    }

    @Override
    public void onReturn(boolean handler) {

        if (!VerifyUtil.isEmpty(data.getAreaInfo()) || !VerifyUtil.isEmpty(data.getKeyword()) || !VerifyUtil.isEmpty(data.getScId())) {
            data.setAreaInfo("");
            data.setKeyword("");
            data.setScId("");
            data.setPage("1");
            getData();
            return;
        }
        if (handler && isShowKeyboard()) {
            hideKeyboard();
            return;
        }
        finish();

    }

    @Override
    public void onActivityResult(int req, int res, @Nullable Intent intent) {

        super.onActivityResult(req, res, intent);
        if (res == RESULT_OK && intent != null) {
            switch (req) {
                case Constant.CODE_CATE:
                    data.setScId(intent.getStringExtra(Constant.DATA_ID));
                    break;
                case Constant.CODE_AREA:
                    String areaInfo = intent.getStringExtra("area_info");
                    data.setAreaInfo(areaInfo);
                    break;
            }
            data.setPage("1");
            getData();
        }

    }

    //自定义方法

    private void getData() {

        mainPullRefreshView.setLoad();
        vm.getShopList(data);

    }

}
